import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.net.http.HttpResponse;

public class HttpClient {
    private Socket socket=null;


    public HttpClient(String serverIp,int port) throws UnknownHostException, IOException {
       //初始化socket
        socket=new Socket(serverIp,port);
    }

    //通过get方法发起一个HTTP get请求

    public void get(String path) throws IOException {
        //构造HTTP结构的字符串
        try(InputStream inputStream=socket.getInputStream();
        OutputStream outputStream=socket.getOutputStream()){
         String firstLine="GET "+path+" HTTP/1.1\r\n";
         String headers="Host: "+socket.getInetAddress().getHostAddress()+":"+
         socket.getPort()+"\r\n";
         String blankLine="\n";
         String httpRequest=firstLine+headers+blankLine;
         //将HTTP请求写入输出流
         outputStream.write(httpRequest.getBytes());
         outputStream.flush();

         //发送出请求之后，还需要读取请求
         byte[] bytes=new byte[1024*1024];
         int n=inputStream.read(bytes);
         String httpResponse=new String(bytes,0,n);
         System.out.println(httpResponse);
        }catch(IOException e){
            e.printStackTrace();
        }
        return ;
    }

}
